
package org.apache.ocean.server;

import org.apache.ocean.*;
import java.util.concurrent.*;
import java.util.logging.*;
import org.apache.commons.lang.time.*;

/**
 *
 * @author  Jason Rutherglen
 */
public class TimedTask implements Runnable, Callable {
  public static Logger log = Logger.getLogger(TimedTask.class.getName());
  public Callable callable;
  public Runnable runnable;
  
  public TimedTask() {}
  
  public TimedTask(Callable callable) {
    if (callable == null) throw new IllegalArgumentException("callable null");
    this.callable = callable;
  }
  
  public TimedTask(Runnable runnable) {
    if (runnable == null) throw new IllegalArgumentException("runnable null");
    this.runnable = runnable;
  }
  
  public void setCallable(Callable callable) {
    this.callable = callable;
  }
  
  public Object call() throws Exception {
    if (runnable == null && callable == null) return null;
    long startTime = System.currentTimeMillis();
    try {
      Object result = null;
      if (callable != null) {
        result = callable.call();
      } else if (runnable != null) {
        runnable.run();
      }
      long endTime = System.currentTimeMillis();
      if (result instanceof TaskLogXML) {
        TaskLogXML taskLogXML = (TaskLogXML)result;
        taskLogXML.durationMillis = new CLong(endTime - startTime);
      }
      return result;
    } finally {
    }
  }
  
  public void run() {
    try {
      if (callable != null) {
        callable.call();
      } else if (runnable != null) {
        runnable.run();
      }
    } catch (Throwable ex) {
      log.log(Level.SEVERE, "", ex);
    } finally {
    }
  }
}
